from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from ..auth import RefreshToken
from ..models import User
from ..serializers import UserSerializer
import logging
import json
from datetime import timedelta

# 获取logger
logger = logging.getLogger(__name__)

# 添加一个简单的测试视图
@api_view(['GET'])
@permission_classes([AllowAny])
@authentication_classes([])  # 跳过认证
def test_api(request):
    """
    测试API是否可用
    """
    return Response({'message': 'API is working!'}, status=status.HTTP_200_OK)

class LoginView(APIView):
    """
    用户登录视图
    """
    permission_classes = [AllowAny]
    authentication_classes = []  # 明确跳过所有认证

    def post(self, request):
        logger.info("\n\n====== 新的登录请求 ======")
        logger.info(f"请求方法: {request.method}")
        logger.info(f"请求头: {request.headers}")
        
        # 尝试读取原始请求体
        try:
            body = request.body.decode('utf-8')
            logger.info(f"原始请求体: {body}")
            # 尝试解析JSON
            try:
                import json
                json_data = json.loads(body)
                logger.info(f"JSON解析结果: {json_data}")
            except json.JSONDecodeError as e:
                logger.warning(f"无法解析JSON: {str(e)}")
        except Exception as e:
            logger.error(f"无法读取原始请求体: {str(e)}")
        
        # 打印请求数据
        logger.info(f"请求数据 (data): {request.data}")
        try:
            logger.info(f"请求数据类型: {type(request.data)}")
            logger.info(f"请求POST数据: {request.POST}")
        except Exception as e:
            logger.error(f"无法获取请求数据类型: {str(e)}")
        
        # 显示当前数据库中的用户
        try:
            all_users = User.objects.all()
            logger.info(f"数据库中的用户列表: {[{'id': u.id, 'username': u.username} for u in all_users]}")
        except Exception as e:
            logger.error(f"无法获取用户列表: {str(e)}")
        
        username = request.data.get('username')
        password = request.data.get('password')
        remember_me = request.data.get('remember_me', True)  # 默认为True
        
        logger.info(f"提取的用户名: {username}")
        logger.info(f"记住登录: {remember_me}")

        if not username or not password:
            logger.warning("缺少用户名或密码")
            return Response({'error': '用户名和密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        user = None
        # 尝试通过用户名查找用户
        try:
            user = User.objects.get(username=username)
            logger.info(f"通过用户名找到用户: {user.username}, id: {user.id}")
        except User.DoesNotExist:
            logger.info(f"未找到用户名为 {username} 的用户")
            pass
        except Exception as e:
            logger.error(f"查询用户时发生异常: {str(e)}")

        # 如果未找到用户，则尝试通过邮箱查找
        if not user:
            try:
                user = User.objects.get(email=username)
                logger.info(f"通过邮箱找到用户: {user.email}, id: {user.id}")
            except User.DoesNotExist:
                logger.warning(f"未找到邮箱为 {username} 的用户")
                return Response({'error': '用户名或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)
            except Exception as e:
                logger.error(f"通过邮箱查询用户时发生异常: {str(e)}")
                return Response({'error': f'查询用户时出错: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 验证密码
        logger.info(f"校验密码: 输入='{password}', 存储='{user.pwd}'")
        if user.pwd != password:
            logger.warning("密码验证失败")
            return Response({'error': '用户名或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)

        logger.info("密码验证成功")
        
        # 创建Token
        try:
            refresh = RefreshToken.for_user(user)
            
            # 如果记住登录状态，设置token有效期为30天
            if remember_me:
                refresh.set_exp(lifetime=timedelta(days=30))
                logger.info(f"设置token有效期为30天")
            
            logger.info(f"为用户 {user.username} 生成了token")
            
            # 序列化用户信息
            serializer = UserSerializer(user)
            logger.info(f"序列化的用户数据: {serializer.data}")
            
            # 构建响应
            response = {
                'token': str(refresh.access_token),
                'refresh': str(refresh),
                'user': serializer.data
            }
            logger.info(f"返回的响应数据: {response}")
            logger.info("登录成功，返回响应")
            return Response(response)
        except Exception as e:
            logger.error(f"生成token时出错: {str(e)}", exc_info=True)
            return Response({'error': f'生成令牌时出错: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserInfoView(APIView):
    """
    获取用户信息视图
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        print(f"Getting user info for user_id: {request.user.id}")
        try:
            # 在DRF JWT中，request.user可能不是User模型实例，需要获取正确的User对象
            user = User.objects.get(id=request.user.id)
            serializer = UserSerializer(user)
            return Response({
                'data': serializer.data
            })
        except Exception as e:
            print(f"Error getting user info: {str(e)}")
            return Response({'error': '获取用户信息失败'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def logout(request):
    """
    用户登出
    """
    # 客户端应该删除token，这里只是返回成功响应
    return Response({'message': '登出成功'}, status=status.HTTP_200_OK) 